'''
get img with person and car in D435 data
keep valid annotation from labels

5 wuzhuangrenyuan 
6 yichangmubiao 
7 wurenche
8 zhenren
10 qiche
'''
import os
import re
import shutil

#num = 1
LPATH = '/home/s/Pictures/D435/labels/train/'
IPATH = '/home/s/Pictures/D435/images/train/'
KEEP_PATH = '/home/s/Pictures/D435/keep/'
UNKEEP_PATH = '/home/s/Pictures/D435/unkeep/'
for file in os.listdir(path=LPATH):
    
    with open(LPATH+file, "r+", encoding='utf-8') as f:
    # readlines()：读取文件全部内容，以列表形式返回结果
        data = f.readlines()
        KEEP = 0
        changed_data = ''
        for item in data:
            text = list(item)    #将字符串转换为列表，列表的每一个元素为一个字符
            print(text[0])
            if (text[0]=='5'):
                # wuzhuangrenyuan | person
                KEEP = 1
                text[0]=='1'
                text = ''.join(text)     #将列表重新连接为字符串
                print("KEEP")
            if (text[0]=='6'):
                # yichangmubiao | person
                KEEP = 1
                text[0]=='1'
                print("KEEP")
            if (text[0]=='7'):
                # wurenche | car
                KEEP = 1
                text[0]=='3'
                print("KEEP")
            if (text[0]=='8'):
                # zhenren | person
                text[0]=='1'
                KEEP = 1
                print("KEEP")
            if (text[0]=='1'):
                if (text[1]=='0'):
                    # car
                    text[0]=='3'
                    text[1]==' '
                    KEEP = 1
                    print("KEEP")
        text = ''.join(text)     #将列表重新连接为字符串
        changed_data = changed_data+text

        dirname = os.path.splitext(file)[0]

        if (KEEP == 1):
            if shutil.os.path.exists(os.path.join(IPATH, f'{dirname}.jpg')): 
                shutil.move(os.path.join(IPATH, f'{dirname}.jpg'), os.path.join(KEEP_PATH, f'{dirname}.jpg'))
                newf = open(KEEP_PATH+file, 'a', encoding='utf-8')
                newf.write(changed_data)
                newf.close()
        else:
            if shutil.os.path.exists(os.path.join(IPATH, f'{dirname}.jpg')): 
                shutil.move(os.path.join(IPATH, f'{dirname}.jpg'), os.path.join(UNKEEP_PATH, f'{dirname}.jpg'))
                shutil.move(os.path.join(LPATH, f'{dirname}.txt'), os.path.join(UNKEEP_PATH, f'{dirname}.txt'))            

